// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const tmpid = 'Vhv2KqnlrhpiLeEoCjsAJSht3-F6dkpYCFsAZE_OzsI'
// 云函数入口函数
 function addPreZero(num, len = 2) {
	var t = (num + '').length,
		s = '';
	for (var i = 0; i < len - t; i++) {
		s += '0';
	}
	return s + num;
}
function getDatetime(date) {
	return date.getFullYear() + '-' + addPreZero(date.getMonth() + 1) + '-' + addPreZero(date.getDate()) + ' ' + addPreZero(date.getHours()) + ':' + addPreZero(date.getMinutes()) + ':' + addPreZero(date.getSeconds())
}
exports.main = async (event, context) => {
	//外面传参的情况下隐藏掉这个
	//op=examine的时候代表审核，否则为获取门店信息
	event = {
		_id: '0ec685215e3c72570b60fe40648b6406',
		op: 'examine',
		status: 2,
		tips:''
	}
	let shop = await db.collection('shop').doc(event._id).get()
	if (!shop.data) {
		return {
			status: 'fail',
			msg: '门店不存在'
		}
	}
	shop = shop.data
	if (!event.op) {
		const result = await cloud.getTempFileURL({
			fileList: [shop.cover_image, shop.license_image],
		})
		console.log(result)
		return {
			status: 'success',
			shop: shop,
			files: result.fileList
		}
	} else if (event.op == 'examine') {
		let status = event.status
		if (status == shop.status) {
			return {
				status: 'fail',
				msg: '状态未改变'
			}
		}
		let update = {
			examine:shop.examine,
			status
		}
		let newExamine = {
			status:event.status,
			time:new Date()
		}
		if(event.tips){
			newExamine.tips = event.tips
		}
		update.examine = [newExamine].concat(update.examine)
		if (status == 2) {
			try {
				const result = await cloud.openapi.subscribeMessage.send({
					touser: shop._openid,
					page: 'pages/shops/index',
					data: {
						thing5: {
							value: shop.license_name
						},
						name4: {
							value: shop.apply_name
						},
						date3: {
							value: getDatetime(new Date())
						},
						thing2: {
							value: '审核通过'
						},
						thing6: {
							value: event.tips ? event.tips : '武汉加油！中国加油！'
						}
					},
					templateId: tmpid
				})
				console.log(result)
			} catch (err) {
				console.error(err)
			}
		}else if(status==3){
			try {
				const result = await cloud.openapi.subscribeMessage.send({
					touser: shop._openid,
					page: 'pages/shopApply/index?_id='+shop._id,
					data: {
						thing5: {
							value: shop.license_name
						},
						name4: {
							value: shop.apply_name
						},
						date3: {
							value: getDatetime(new Date())
						},
						thing2: {
							value: '审核失败'
						},
						thing6: {
							value: event.tips ? event.tips : '武汉加油！中国加油！'
						}
					},
					templateId: tmpid
				})
				console.log(result)
			} catch (err) {
				console.error(err)
			}
		}
		return await db.collection('shop').doc(event._id).update({data:update})
	}
	console.log(shop)

}